package api

import (
	"net"
	"strings"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/pkg/errors"
	"gorm.io/gorm"

	"gitee.com/sillyman/PingHostsWebView/models"
	"gitee.com/sillyman/PingHostsWebView/modules/config"
	"gitee.com/sillyman/PingHostsWebView/modules/db"
)

// GetPingerSummaries 列出所有的总结
func GetPingSummaries(c echo.Context) error {
	summaries := make([]models.PingSummary, 0, 128)

	dbConn := db.MustObtainMainDB()
	if err := dbConn.Limit(config.AllowMaxNumHosts).Find(&summaries).Error; err != nil {
		return newHttpErrReadDB(err)
	}
	db.ReleaseMainDB()

	return respJSON200(c, summaries)
}

// ClearAllSummaries 清零所有计数器
func ClearAllSummaries(c echo.Context) error {
	dbConn := db.MustObtainMainDB()
	defer db.ReleaseMainDB()
	err := dbConn.Session(&gorm.Session{AllowGlobalUpdate: true}).
		Model(&models.PingSummary{}).
		Select(
			"succeed_count",
			"failed_count",
			"max_rtt",
			"min_rtt",
			"avg_rtt",
			"sum_rtt_squares",
			"mdev_rtt",
			"total_rtt",
			"last_rtt",
			"last_rtt",
			"last_failed_at",
			"updated_at", // 需要更新时间，前端的页面才能通过 websocket 进行更新
		).
		Updates(models.PingSummary{UpdatedAt: time.Now()}).Error
	if err != nil {
		return newHttpErrWriteDB(err)
	}

	return resp204(c)
}

// SetPingSummaryComment 设置备注
func SetPingSummaryComment(c echo.Context) error {
	ip := net.ParseIP(c.Param("ip"))
	if ip == nil {
		return newHttpErrBadParam(errors.New("This is not a valid textual representation of an IP address"))
	}
	comment := strings.TrimSpace(c.QueryParam("v"))

	dbConn := db.MustObtainMainDB()
	defer db.ReleaseMainDB()
	if err := dbConn.Model(&models.PingSummary{}).Where("ip = ?", ip.String()).Update("comment", comment).Error; err != nil {
		return newHttpErrWriteDB(err)
	}

	return resp202(c)
}
